﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BluePortal.Medias.Core;


namespace BluePortal.QuikStart.UserControls
{
    public partial class AddUpdateChannel : System.Web.UI.UserControl
    {
        private Guid chid = Guid.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["chid"] != null)
                {
                    chid = new Guid(Request.QueryString["chid"]);
                    ViewState["chid"] = chid;
                    Channel c = new BCChannel().FindByID(chid);
                    tbChannelName.Text = c.ChannelName;
                    tbDescription.Text = c.ChannelDescription;
                    cbPrivate.Checked = c.IsPrivate;
                    cbLive.Checked = c.AllowLive;
                    imgLogo.ImageUrl = "~/Images/ChannelHandler.ashx?chid=" + chid.ToString();
                }
                else
                {
                    imgLogo.Visible = false;
                    btDeleteChannel.Visible = false;
                }
            }
            if (ViewState["chid"] != null)
            {
                chid = (Guid)ViewState["chid"];
            }
        }

        protected void btDeleteChannel_Click(object sender, EventArgs e)
        {
            if (chid != Guid.Empty)
            {
                new BCChannel().Delete(new Channel() { CHID = chid });
                Response.Redirect(Request.Url.AbsolutePath);
            }
        }

        protected void btAddChannel_Click(object sender, EventArgs e)
        {
            Channel c;
            BCChannel bc = new BCChannel();  
            if (chid == Guid.Empty)
            {
                c = new Channel();
            }
            else
            {
                c = bc.FindByID(chid);
            }
            c.ChannelName = tbChannelName.Text;
            c.ChannelDescription = tbDescription.Text;
            if (fuChannelLogo.FileName != string.Empty)
                c.ChannelLogo = fuChannelLogo.FileBytes;
            c.IsPrivate = cbPrivate.Checked;
            c.AllowLive = cbLive.Checked;
            c.Owner = Page.User.Identity.Name;
            c.CreationDate = DateTime.Now;

            if (c.CHID == Guid.Empty)
                bc.Create(c);
            else
            {
                bc.Update(c);
                Response.Redirect(Request.Url.AbsolutePath);
            }

            tbChannelName.Text = string.Empty;
            cbPrivate.Checked = false;
            cbLive.Checked = false;
            tbDescription.Text = string.Empty;
        }
    }
}